package bg.openid.joid;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.util.Hashtable;
import java.util.Properties;
import java.util.StringTokenizer;

import org.verisign.joid.AssociationRequest;
import org.verisign.joid.AssociationResponse;
import org.verisign.joid.Crypto;
import org.verisign.joid.DiffieHellman;
import org.verisign.joid.Response;
import org.verisign.joid.consumer.Util;

public class UtilAssociate {
	private static UtilAssociate instance = new UtilAssociate();
	Hashtable<String, Properties> hPsecret = new Hashtable<String, Properties>();
	
	public Properties getPSecret(String id) throws Exception{
		String key = this.getServerUrl(id);
		Properties p = hPsecret.get(key);
		if (p == null){
			p = fetchPropertiesAssociate(key);
			if (p != null){
				this.hPsecret.put(key, p);
			}
		}
		return p;
	}

	

	public static UtilAssociate getInstance() {
		return instance;
	}
	
	public Properties fetchPropertiesAssociate(String destination) throws Exception {
		DiffieHellman dh = DiffieHellman.getDefault();
		Crypto crypto = new Crypto();
		crypto.setDiffieHellman(dh);

		AssociationRequest ar = AssociationRequest.create(crypto);

		Response response = Util.send(ar, destination);
		System.out.println("Response=" + response + "\n");

		AssociationResponse asr = (AssociationResponse) response;

		Properties props = new Properties();
		props.setProperty("handle", asr.getAssociationHandle());
		props.setProperty("publicKey", Crypto.convertToString(asr.getDhServerPublic()));
		props.setProperty("encryptedKey", Crypto.convertToString(asr.getEncryptedMacKey()));

		BigInteger privateKey = dh.getPrivateKey();
		props.setProperty("privateKey", Crypto.convertToString(privateKey));
		props.setProperty("modulus", Crypto.convertToString(DiffieHellman.DEFAULT_MODULUS));

		props.setProperty("_dest", destination);
        return props;
		
	}

	
	public String getServerUrl(String id){
		if (id.indexOf("myopenid.com") > 0){
			return ("http://www.myopenid.com/server");
		}
		if (id.indexOf("pip.verisignlabs.com") > 0){
			return ("http://pip.verisignlabs.com/server");
		}
		return null;
	}

	public void associateFull(String identity) {
		 String server = getServerUrl(identity);
	}

}
